package com.ep.thirdPlatformProject.system.config.xxlJob;


import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@Slf4j
@ConfigurationProperties(prefix = "xxl.job")
public class XxlJobProperties {

    /**
     * admin地址
     */
    private String adminAddresses;

    /**
     * admin地址
     */
    private String appName;

    /**
     * 地址
     */
    private String address;

    /**
     * 地址
     */
    private String ip;

    /**
     * 端口
     */
    private int port;

    /**
     * token
     */
    private String accessToken;

    /**
     * 日志地址
     */
    private String logPath;

    /**
     * 日志保存时长
     */
    private int logRetentionDays;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;
    /**
     * 针对多网卡、容器内部署等情况，可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP；
     *      1、引入依赖：
     *          <dependency>
     *             <groupId>org.springframework.cloud</groupId>
     *             <artifactId>spring-cloud-commons</artifactId>
     *             <version>${version}</version>
     *         </dependency>
     *      2、配置文件，或者容器启动变量
     *          spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
     *      3、获取IP
     *          String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
     */

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        log.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAppname(appName);
        xxlJobSpringExecutor.setAddress(address);
        // 替换为自动注册的方式
        try (InetUtils inetUtils = new InetUtils(new InetUtilsProperties())) {
            // docker等容器网段查找适用ip地址
            String adminIp = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
            xxlJobSpringExecutor.setIp(adminIp);
        } catch (Exception e) {
            log.error(">>>>>>>>>>> xxl-job config init error,ip错误:{}", e.getMessage());
        }
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setAccessToken(accessToken);
        xxlJobSpringExecutor.setLogPath(logPath);
        xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);

        return xxlJobSpringExecutor;
    }

}
